package ThreadTest.ix;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class TestSemaphore {

    public static void main(String[] args) {
        //线程池
        ExecutorService exec = Executors.newCachedThreadPool();
        //只能5个线程同时访问
        final Semaphore semp = new Semaphore(5);
        //模拟20个客户端访问
        for(int index = 0;index<20;index++){
            final int num = index;
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    try{
                        semp.acquire();
                        System.out.println("Accessing: "+num);
                        Thread.sleep(5000);
                        semp.release();
                        System.out.println("---------------"+semp.availablePermits());
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            };
            exec.execute(run);
        }
        exec.shutdown();
    }
}
